package ru.gelin.android.multiplier;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import static ru.gelin.android.multiplier.OperationsHistoryOpenHelper.*;

public class OperationsHistory {

    static final String DB_NAME = "ops_history";

    static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

    SQLiteDatabase db;

    public OperationsHistory(Context context) {
        this.db = new OperationsHistoryOpenHelper(context, DB_NAME).getWritableDatabase();
    }

    public OperationsHistoryItem add(Operation op) {
        OperationsHistoryItem item = new OperationsHistoryItem(op);
        ContentValues values = new ContentValues();
        values.put(DATE_COLUMN, DATE_FORMAT.format(item.date));
        values.put(NUM1_COLUMN, item.operation.getNumber1());
        values.put(NUM2_COLUMN, item.operation.getNumber2());
        values.put(OP_COLUMN, String.valueOf(item.operation.getType()));
        db.insert(HISTORY_TABLE, null, values);
        return item;
    }

    public OperationsHistoryItem getLatest() {
        Cursor cursor = getCursor();    //TODO optimize?
        if (!cursor.moveToFirst()) {
            return null;
        }
        OperationsHistoryItem item = null;
        try {
            item = new OperationsHistoryItem(cursor);
        } catch (ParseException e) {
            return null;
        }
        cursor.close();
        return item;
    }

    Cursor getCursor() {
        Cursor cursor = db.query(HISTORY_TABLE,
                new String[] { DATE_COLUMN, NUM1_COLUMN, NUM2_COLUMN, OP_COLUMN },
                null,
                null,
                null,
                null,
                DATE_COLUMN + " DESC");
        return cursor;
    }

}
